{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3a79ef54-63e6-429f-ba9f-590b736a7f29",
   "metadata": {},
   "source": [
    "# 3.13 对向量求偏导数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c90a18b9-d8e8-431c-856c-35f1e4ed05e1",
   "metadata": {},
   "source": [
    "### 1.任务描述\n",
    "函数的表达式为：$F(X,Y)=X^2+2Y^2+1$，其中X,Y是向量，求：\n",
    "\n",
    "- 在$X={(1,2,3)}^T$处，求偏导数$\\frac{\\partial F(X,Y)}{\\partial X}$\n",
    "- 在$Y={(4,5,6)}^T$处，求偏导数$\\frac{\\partial F(X,Y)}{\\partial Y}$"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "8d7baa9c-93a2-42f3-a3c1-231cdb587f2d",
   "metadata": {},
   "source": [
    "### 2.知识准备\n",
    "\n",
    "见教程。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74ad989a-9b82-43e1-b841-e74284cd5936",
   "metadata": {},
   "source": [
    "### 3.任务分析\n",
    "\n",
    "对向量求偏导数，得到的偏导数依然是向量。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "435c6090-cfda-4f46-a550-22a368e41e4a",
   "metadata": {},
   "source": [
    "### 4.任务实施\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ec75eb6c-5da3-467d-a471-ca3b47242dd6",
   "metadata": {},
   "source": [
    "执行代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2ae9da58-e339-4d22-9f8d-ca255711d89e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor(\n",
      "[[34.]\n",
      " [55.]\n",
      " [82.]], shape=(3, 1), dtype=float32)\n",
      "tf.Tensor(\n",
      "[[2.]\n",
      " [4.]\n",
      " [6.]], shape=(3, 1), dtype=float32)\n",
      "tf.Tensor(\n",
      "[[16.]\n",
      " [20.]\n",
      " [24.]], shape=(3, 1), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "# 1，创建可训练向量\n",
    "X=tf.Variable([[1.],[2.],[3.]])\n",
    "Y=tf.Variable([[4.],[5.],[6.]])\n",
    "# 2，创建tape对象\n",
    "with tf.GradientTape() as tape:\n",
    "    # 3，定义函数\n",
    "    F=tf.square(X) +2*tf.square(Y)+1 \n",
    "    # 4，求偏导数\n",
    "    dF_dX,dF_dY=tape.gradient(F,[X,Y])\n",
    "# 函数值\n",
    "print(F)\n",
    "# 对X求偏导数\n",
    "print(dF_dX)\n",
    "# 对Y求偏导数\n",
    "print(dF_dY)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f2c61db-4b69-49f9-9b22-f6d2642a056d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
